package com.zhangmeng.online.exam.controller;

import com.zhangmeng.online.exam.dao.PermissionDao;
import com.zhangmeng.online.exam.dao.RoleDao;
import com.zhangmeng.online.exam.dto.Result;
import com.zhangmeng.online.exam.entity.Permission;
import com.zhangmeng.online.exam.entity.Question;
import com.zhangmeng.online.exam.entity.Role;
import com.zhangmeng.online.exam.entity.User;
import com.zhangmeng.online.exam.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author zm
 * @date 2025/3/6 17:27
 * @version: 1.0
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @RequestMapping("/list")
    public Result list(Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(PageUtils.getPageNum(pageNum), pageSize, Sort.Direction.DESC, "addTime");
        Page<Role> all = roleDao.findAll(pageable);
        List<Role> list = roleDao.findAll();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Role role : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", role.getId());
            map.put("name", role.getName());
            map.put("desc", role.getDescription());
            map.put("type_name", role.getType().name());
            resultList.add(map);
        }
        return Result.success(pageNum, pageSize, all.getTotalElements(), resultList);
    }


    @RequestMapping("/getRoleById")
    public Result getRoleById(Long id) {
        Role role = roleDao.findById(id).get();

        Map<String, Object> map = new HashMap<>();
        map.put("id", role.getId());
        map.put("name", role.getName());
        map.put("desc", role.getDescription());
        map.put("type_name", role.getType().name());

        return Result.success(map);
    }

    @RequestMapping("/getRoleTypes")
    public Result getRoleTypes() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Role.Type type : Role.Type.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("type_name", type.name());
            map.put("type_desc", type.getDesc());
            resultList.add(map);
        }
        return Result.success(resultList);
    }

    @RequestMapping("/saveRole")
    public Result saveRole(@RequestBody @RequestParam Map<String, Object> params) {

        String id = params.get("id").toString();
        String name = params.get("name").toString();
        String desc = params.get("desc").toString();
        String type = params.get("type").toString();

        Role role;

        if (id != null && !id.isEmpty()) {
            role = roleDao.findById(Long.parseLong(id)).get();
        } else {
            role = new Role();
        }

        role.setName(name);
        role.setDescription(desc);
        role.setType(Role.Type.valueOf(type));
        roleDao.save(role);

        return Result.success(null);
    }

    @RequestMapping("/delete")
    public Result delete(Long id) {
        roleDao.deleteById(id);
        return Result.success(null);
    }

    @RequestMapping("/updatePermission")
    public Result updatePermission(@RequestBody @RequestParam Map<String, Object> params) {
        Long roleId = Long.parseLong(params.get("id").toString());
        String permissionIds = params.get("permissionIds").toString();
        List<Long> permissionIdList = new ArrayList<>();
        for (String permissionId : permissionIds.split(",")) {
            permissionIdList.add(Long.parseLong(permissionId));
        }
        List<Permission> permissionList = permissionDao.findAllById(permissionIdList);
        Role role = roleDao.getById(roleId);
        role.setPermissions(new HashSet<>(permissionList));
        roleDao.save(role);
        return Result.success(null);
    }

    @RequestMapping("/getPermissionsByRole")
    public Result getPermissionsByRole(Long roleId) {
        Role role = roleDao.getById(roleId);
        Set<Permission> permissionList = role.getPermissions();
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (Permission permission : permissionList) {
//            if (permission.getParent() == null){
//                List<Permission> children = permission.getChildren();
//
//                Map<String, Object> map = new HashMap<>();
//                map.put("id", permission.getId());
//                map.put("name", permission.getName());
//                map.put("desc", permission.getDescription());
//                map.put("url", permission.getUrl());
//                map.put("sort", permission.getSort());
//                map.put("parentId", permission.getParent() == null ? 0L : permission.getParent().getId());
//
//                List<Map<String, Object>> childList = new ArrayList<>();
//
//                if (!children.isEmpty()){
//                    for (Permission child : children) {
//                        if (permissionList.contains(child)){
//                            Map<String, Object> childMap = new HashMap<>();
//                            childMap.put("id", child.getId());
//                            childMap.put("name", child.getName());
//                            childMap.put("desc", child.getDescription());
//                            childMap.put("url", child.getUrl());
//                            childMap.put("sort", child.getSort());
//                            childMap.put("parentId", child.getParent() == null ? 0L : child.getParent().getId());
//                            childList.add(childMap);
//                        }
//                    }
//                }
//
//                map.put("children", childList);
//
//                resultList.add(map);
//            }


            Map<String, Object> map = new HashMap<>();
            map.put("id", permission.getId());
            map.put("name", permission.getName());
            map.put("desc", permission.getDescription());
            map.put("url", permission.getUrl());
            map.put("sort", permission.getSort());
            map.put("parentId", permission.getParent() == null ? 0L : permission.getParent().getId());
            map.put("children", new ArrayList<>());

            resultList.add(map);
        }

        return Result.success(resultList);
    }
}
